<template>
  <div class="app-container">
    <el-form :model="form" ref="formRef" :scroll-to-error="true" v-loading="formLoading">
      <el-space direction="vertical">
        <div shadow="never" class="assess">
          <el-row justify="center" class="task-title assess-title">
            <el-form-item label="当前任务编号：" prop="assessCode">
              <span>{{ form.assessCode }}</span>
            </el-form-item>
            <el-form-item label="当前任务名称：" prop="assessName">
              <span>{{ form.assessName }}</span>
            </el-form-item>
          </el-row>
          <el-row justify="center" class="assess-title">
            <el-form-item label="评估区域：" prop="list">
              {{ form.list?.map(item => {
                let area = []
                item.ppName && area.push(item.ppName)
                item.cityName && area.push(item.cityName)
                item.name && area.push(item.name)
                return area
              }).map(item => item.join('-')).join('、')
              }}
            </el-form-item>
            <el-form-item label="房屋基础数据：" prop="houseDataFlag">
              {{ houseBasicData.find(item => item.value == form.houseDataFlag)?.name }}
            </el-form-item>
            <el-form-item label="地震输入方式：" prop="seismicInputMode">
              <span>
                {{
                  inputMode?.map(item => {
                    return seismicInputMode.find(cur => cur.value == item).name
                  }).join('-')
                }}
              </span>
            </el-form-item>
          </el-row>
        </div>
      </el-space>
      <template v-if="form.assessType == '1'">
        <el-form :model="calculateForm" ref="calculateFormRef" :inline="true" :rules="calculateFormRules">
          <el-form-item label="评估内容：" prop="selectedVal" style="margin-bottom: 20px;">
            <el-checkbox-group v-model="calculateForm.selectedVal" @change="selectedValChange">
              <el-checkbox v-for="item in assessObj" :key="item.value" :label="item.value">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="上年度GDP：" prop="templateName" style="margin-bottom: 20px;min-width: 210px"
            class="templateName">
            <template v-if="!(calculateForm.templateName || form.gdpExist == '1')">
              <el-button plain @click="importExcel(false)">导入</el-button>
            </template>
            <template v-else>
              <el-space>
                <el-link type="primary" :underline="false" @click="downloadFile">上年度GDP.xlsx</el-link>
                <el-button plain @click="importExcel(true)">重新导入</el-button>
              </el-space>
            </template>
          </el-form-item>
        </el-form>
        <el-row style="margin: 10px 0;">
          <el-button plain @click="calculateZoningValues">计算区划值</el-button>
        </el-row>
        <el-space direction="vertical">
          <div shadow="never" class="assess">
            <el-row>
              <el-form-item label="区划" style="display:block;width: 100%;" prop="assessObj">
                <el-row justify="space-between">
                  <el-radio-group v-model="form.assessObj" @click="resetTable">
                    <el-radio v-for="item in assessObj" :key="item.value" :label="item.value" size="large"
                      v-show="assessObjData?.includes(item.value)">
                      {{ item.name }}
                    </el-radio>
                  </el-radio-group>
                </el-row>
              </el-form-item>
              <el-form-item label="地震输入" style="display:block;width: 100%;" prop="seismicInputMode1">
                <el-row justify="space-between">
                  <el-radio-group v-model="form.seismicInputMode1" @click="resetTable">
                    <el-radio v-for="item in inputMethods('probability')" :key="item.value" :label="item.value"
                      size="large" v-show="inputMode?.includes(item.value)">
                      {{ item.name }}
                      <el-select v-model="form.condition0" v-show="form.seismicInputMode1 == '0' && item.value == '0'">
                        <el-option v-for="item in dictData.intensity" :key="item.dictItemId" :label="item.dictItemName"
                          :value="item.dictItemCode" />
                      </el-select>
                      <el-select v-model="form.condition1" v-show="form.seismicInputMode1 == '1' && item.value == '1'">
                        <el-option v-for="item in dictData.probability" :key="item.dictItemId" :label="item.dictItemName"
                          :value="item.dictItemCode" />
                      </el-select>
                    </el-radio>
                  </el-radio-group>
                </el-row>
              </el-form-item>
              <el-row>
                <!-- <el-form-item label="T年" prop="years">
                  <el-select v-model="form.years">
                    <el-option v-for="item in form.year.split(',')" :key="item" :label="item" :value="item" />
                  </el-select>
                </el-form-item> -->
                <!-- <el-option v-for="item in dictData.years" :key="item.dictItemName" :label="item.dictItemName"
                      :value="item.dictItemName.slice(0, item.dictItemName.length - 1)" /> -->
                <!-- <el-form-item label="T年" prop="years">
                  <span style="color: var(--el-input-text-color, var(--el-text-color-regular))">{{ form.years }}年</span>
                </el-form-item> -->
              </el-row>
            </el-row>
          </div>
        </el-space>
        <el-row style="margin: 10px 0">
          <el-button type="primary" @click="clickZoningValue">查看区划值</el-button>
          <el-button type="primary" @click="clickZoningMap">查看区划图</el-button>
        </el-row>
        <!--查询结果表-->
        <el-table v-if="zoningValueBool" v-loading="loading" ref="tableRef" :data="dataList" stripe>
          <el-table-column label="省" align="center" prop="province" />
          <el-table-column label="市" align="center" prop="city" />
          <el-table-column label="区/县" align="center" prop="county" />
          <!-- <el-table-column label="T年" prop="condition" align="center" min-width="280" /> -->
          <el-table-column align="center" prop="calculatedValue">
            <template #header>
              <div>风险区划计算值</div>
              <span v-show="form.assessObj == '1'">（人）</span>
            </template>
          </el-table-column>
          <el-table-column label="风险区划等级" align="center" prop="qhLevel" />
        </el-table>
        <!-- <pagination v-if="zoningValueBool" style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="paginationData.page"
                  v-model:limit="paginationData.rows" @pagination="getList" /> -->
        <div v-if="zoningMapBool" style="position: relative;">
          <indexMap :paramsSql="paramsSql" :taskGeom="form.coordinateRange" @getLegendHtml="getLegendHtml"
            @showImgcreate="showImgcreate" />
        </div>
        <!--图层图例-->
        <div v-if="showHideLegendDivBool" class="layerMap-legend">
          <!--滚动条-->
          <el-scrollbar max-height="500px">
            <p>图例</p>
            <div><div style="width: 16px;height: 16px;float: left;margin-top: 3px;border: 2px solid #668B8B;"></div><div style="margin-left: 25px;">任务区域</div></div>
            <div v-for="item in layerShowHideArray" :key="item.name" v-show="item.show" v-html="item.legendHtml">
            </div>
          </el-scrollbar>
        </div>
      </template>
      <template v-else>
        <Empty description="无概率评估风险区划" />
      </template>
      <drawingView :open="plotDialog" :formParams="formParams" :title="title" @closeDialog="closeDialog" />
      <ExcelImport v-model:open="importOpen" :uploadParams="uploadParams" @importSuccess="importSuccess" />
    </el-form>
  </div>
</template>

<script setup name="singleRiskZonationConfirm">
import indexMap from '@/map/buildingRiskZoning/singleRiskZonation/confirm/indexMap.vue'
import drawingView from '@/map/components/drawingView/index.vue';
import { getAssessPdQhList, doZoningProbability } from '@/api/buildingRiskZoning/singleRiskZonation/index'
import { getTasks } from '@/api/building/index.js'
import { getDict } from '@/api/system/dict.js'
import { CODE, inputMethods, houseBasicData, seismicInputMode } from '@/views/building/index'
import { assessObj } from '@/views/buildingRiskZoning/singleRiskZonation/index'
import ExcelImport from '@/components/ExcelImport'
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance();
const zoningValueBool = ref(true)
const zoningMapBool = ref(false)
const dataList = ref([])
const loading = ref(false)
const paginationData = ref({
  page: 1,
  rows: 10
})
const total = ref(0)
const taskId = ref('')
const showHideLegendDivBool = ref(false)
const plotDialog = ref(false)
const title = ref('')
const formParams = ref({})

function showImgcreate() {
  plotDialog.value = true
  formParams.value.taskId = form.value.id
  formParams.value.dataType = '1'
  formParams.value.qhType = '0'
  formParams.value.assessType = '1'
  formParams.value.year = form.value.years
  title.value = '风险区划-概率评估风险区划'
}
function clickZoningValue() {
  zoningValueBool.value = true
  zoningMapBool.value = false
  loading.value = true
  const { assessObj, years } = form.value
  getAssessPdQhList({
    taskId: taskId.value, estimateObj: assessObj,
    condition: years
  }).then(res => {
    dataList.value = res.data
    loading.value = false
  }).catch(() => loading.value = false)
  showHideLegendDivBool.value = false
}
const closeDialog = (bool) => {
  plotDialog.value = false;
}
function calculateZoningValues() {
  proxy.$refs.calculateFormRef.validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在计算，请稍候...")
      doZoningProbability({ taskId: taskId.value, selectedVal: calculateForm.value.selectedVal.join(',') }).then(res => {
        proxy.$modal.closeLoading()
        proxy.$modal.msgSuccess(res.message);
      }).catch(() => proxy.$modal.closeLoading())
    }
  })
}
const paramsSql = ref({})
function clickZoningMap() {
  zoningValueBool.value = false
  zoningMapBool.value = true
  const { assessObj, years } = form.value
  paramsSql.value = {
    taskId: taskId.value,
    estimateObj: assessObj,
    condition: years,
    type: '概率'
  }
  // getAssessPdQhList({
  //   taskId: taskId.value, estimateObj: assessObj,
  //   condition: years
  // }).then(res => {
  //   dataList.value = res.data
  // }).catch()
}
const form = ref({})
const formLoading = ref(false)
let inputMode = ref()
const assessObjData = ref()
function getTaskInFo() {
  formLoading.value = true
  getTasks().then(res => {
    if (res.data && res.code == 200) {
      form.value = { ...form.value, ...res.data }
      inputMode.value = res.data.seismicInputMode.split(',')
      form.value.seismicInputMode = res.data.seismicInputMode.split(',').sort((a, b) => a - b)[0]
      form.value.seismicInputMode1 = res.data.seismicInputMode.split(',').sort((a, b) => a - b)[0]
      assessObjData.value = res.data.assessObj.split(',')
      form.value.assessObj = res.data.assessObj.split(',').sort((a, b) => a - b)[0]
      taskId.value = res.data.id
      dictInit()
      uploadParams.value.downloadParams = res.data.list?.map(item => {
        return {
          provinceName: item.ppName,
          cityName: item.cityName,
          countyName: item.name,
          previousGdp: "0"
        }
      })
      uploadParams.value.params = { taskId: taskId.value }
      if (form.value.gdpExist == '1') {
        calculateForm.value.templateName = '上年度GDP.xlsx'
      }
    }
    formLoading.value = false
  }).catch(() => { formLoading.value = false })
}
// 字典项
const dictData = ref({
  years: []
})
const dictInit = () => {
  // getDictData('years', CODE.tn, 'years')
  form.value.years = form.value.year.split(',')[0]
}
// const getDictData = (field, code, formField) => {
//   getDict(code).then(res => {
//     dictData.value[field] = res.data
//     if (formField) {
//       form.value[formField] = res.data[0].dictItemCode
//     }
//   })
// }
const layerShowHideArray = ref([])
//图例
const getLegendHtml = (obj) => {
  if (obj != null) {
    layerShowHideArray.value = [{
      name: obj.name,
      show: obj.show,
      legendHtml: obj.legendHtml
    }];
    showHideLegendDivBool.value = true;// 打开图例面板
  }
}
const resetTable = () => {
  dataList.value = []
}
// 导入
let calculateForm = ref({})
let calculateFormRef = ref()
let calculateFormRules = ref({
  selectedVal: [{ required: true, message: '请选择评估对象', trigger: 'change' }]
})
let importOpen = ref(false)
const uploadParams = ref({
  url: `/enterAssessQh/importExcel`, // 上传地址
  templateName: '上年度GDP.xlsx', // 模板名称
  templateUrl: '/enterAssessQh/downLoad', // 下载地址
  params: {}, // 上传参数
  downloadParams: {}, // 下载参数
  config: true
})
const importExcel = (flag) => {
  if (flag) {
    ElMessageBox.confirm('将会覆盖已导入的上年度GDP文件，是否确定重新导入？', '提示消息',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        cancelButtonClass: 'is-plain'
      }).then(() => {
        importOpen.value = true
      }).catch(() => { });
  } else {
    importOpen.value = true
  }
}
const importSuccess = (file) => {
  calculateForm.value.templateName = file.name
  importOpen.value = false;
  calculateFormRef.value.clearValidate('templateName')
}
const downloadFile = () => {
  proxy.download(`/enterAssessQh/downLoadData`, { taskId: taskId.value }, '上年度GDP.xlsx', true)
}
const selectedValChange = val => {
  if (val.includes('2')) {
    calculateFormRules.value.templateName = [{ required: true, message: '请导入上年度GDP', trigger: 'change' }]
  } else {
    calculateFormRules.value.templateName = ''
    proxy.$refs.calculateFormRef.clearValidate('templateName')
  }
}

onMounted(() => {
  getTaskInFo()
})
</script>

<style lang="scss" scoped>
.assess-dialog.el-dialog .el-dialog__body {
  padding: 20px 20px;
}

.el-form-item.el-form-item--default {
  margin: 10px 5px;
}

.assess-title {
  .el-form-item.el-form-item--default {
    margin: 10px 20px;
  }
}

.currentEventMap {
  position: relative;
}

.currentEventDiv {
  position: absolute;
  z-index: 1;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid gray;
  padding: 0 10px;
  width: 100%;
}

:deep(.el-space.el-space--vertical) {
  width: 100%;

  &>.el-space__item {
    width: 100%;
  }
}

.assess {
  border-radius: 4px;
  border: 1px solid #e4e7ed;

  .task-title {
    font-weight: bold;
    color: #606266;

    :deep(.el-form-item) {

      label,
      .el-form-item__content {
        font-size: 18px;
      }
    }
  }

  .border-bottom {
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-row {
    padding: 0 20px;
  }

  .title {
    font-weight: bold;
  }

  :deep(.column.el-radio-group) {
    flex-direction: column;
    align-items: start;

    &>.el-radio {
      &>.el-radio__label {
        &>.el-space {
          &>.el-space__item:first-of-type {
            margin-right: 50px !important;
          }
        }
      }
    }
  }
}

.layerMap-legend {
  position: absolute;
  right: 10px;
  bottom: 10px;
  min-height: 50px;
  background: #fff;
  padding: 10px;
  overflow: auto;
  min-width: 200px;
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.2);
  border: 1px solid #707070;
  border-radius: 4px;
}

// .layerMap-legend p:first-child{
//   text-align: center;font-weight: bold;
// }
:deep(.el-form-item.templateName) {
  label {
    font-weight: normal;
  }
}
</style>